import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:furaha_mkopo/cache/fm_cache_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_language_tool.dart';
import 'package:furaha_mkopo/net/fm_http_response.dart';
import 'package:furaha_mkopo/page/dialog/address/entity/fm_address_entity.dart';
import 'package:furaha_mkopo/page/dialog/address/fm_address_api.dart';
import 'package:get/get.dart';

class FMNewAddressPage extends StatefulWidget {
  List<String> topList;
  Function(String addressValue) callBack;
  FMNewAddressPage({super.key,required this.topList,required this.callBack});

  static void showAddress(String address,Function(String addressValue) callBack){
    List<String> topList = [];
    if(address.isNotEmpty){
      topList = address.split("|");
    }
    Get.to(
        FMNewAddressPage(
          topList: topList,
          callBack: callBack,
        ),
        opaque: false,
        duration: const Duration(milliseconds: 0));
  }
  @override
  State<FMNewAddressPage> createState() => _FMNewAddressPageState();
}

class _FMNewAddressPageState extends State<FMNewAddressPage> {
  String addressJson = FMCacheTool.getAddressList();
  List<FMAddressMySelfEntity> allList = [];
  List<String> topList = [];
  int currentTopIndex = 0;
  List<FMAddressMySelfEntity> bottomList = [];

  @override
  void initState(){
    super.initState();
    topList = widget.topList;
    if(addressJson == "[]" || addressJson.isEmpty){
      return;
    }
    final List<dynamic> mapList = jsonDecode(addressJson);
    allList = mapList.map((e) => FMAddressMySelfEntity.json(e)).toList();
    if(topList.isEmpty){
      topList = initTopList(allList, topList);
    }
    bottomList = findBottomList();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        Get.back();
      },
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: GestureDetector(
          onTap: (){

          },
          child: Center(
            child: Container(
              height: 504,
              width: 311,
              alignment: Alignment.topCenter,
              margin: const EdgeInsets.symmetric(horizontal: 32),
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/address/ic_address_dialog_bg.png'),
                ),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  generateTitle(),
                  generateTopContent(),
                  const SizedBox(height: 12,),
                  generateBottomBtn()
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget generateTitle(){
    return Container(
      margin: const EdgeInsets.only(top: 18, bottom: 10),
      child: Text(
        FMLanguageTool.getText("Please select a address"),
        style: const TextStyle(color: Color(0xFF333333), fontSize: 20),
      ),
    );
  }

  Widget generateTopContent(){
    return SizedBox(
      width: 287,
      height: 317,
      child: Column(
        children: [
          generateTopList(),
          generateDashLine(),
          generateBottomList()
        ],
      ),
    );
  }

  Widget generateTopList(){
    return Container(
      height: 114,
      margin: const EdgeInsets.only(top: 10,bottom: 8),
      child: ListView.builder(
          itemCount: topList.length,
          padding: EdgeInsets.zero,
          itemBuilder: (context,index){
            return GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: (){
                currentTopIndex = index;
                bottomList = findBottomList();
                setState(() {
                });
              },
              child: Container(
                alignment: Alignment.center,
                margin: const EdgeInsets.symmetric(vertical: 8),
                child: Text(
                  topList[index],
                  style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: currentTopIndex == index
                          ? const Color(0xFF158F05)
                          : const Color(0xFF999999)),
                ),
              ),
            );
          }),
    );
  }

  Widget generateDashLine(){
    return Container(
        margin: const EdgeInsets.symmetric(horizontal: 26),
        child: Image.asset('assets/address/ic_address_dash.png'));
  }

  Widget generateBottomList(){
    return Expanded(
        child: Container(
      margin: const EdgeInsets.symmetric(vertical: 6),
      child: ListView.builder(
          itemCount: bottomList.length,
          padding: EdgeInsets.zero,
          physics: const BouncingScrollPhysics(),
          itemBuilder: (context, index) {
            List<FMAddressMySelfEntity> mList = bottomList;
            final FMAddressMySelfEntity address = mList[index];
            if (address.planned == topList[currentTopIndex]) {
              return Container(
                height: 40,
                alignment: Alignment.center,
                margin: const EdgeInsets.only(
                    top: 16, left: 26, right: 26),
                decoration: const BoxDecoration(
                  color: Color(0xFFFF8800),
                  borderRadius:
                  BorderRadius.all(Radius.circular(20)),
                ),
                child: Text(
                  address.planned??'',
                  style: const TextStyle(
                      color: Color(0xFFFFFFFF), fontSize: 14),
                ),
              );
            }
            return GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                if(currentTopIndex == 0){
                  topList.clear();
                }else {
                  topList = topList.sublist(0,currentTopIndex);
                }
                topList.add(address.planned??'');
                topList = findTopList(allList, topList);
                setState(() {

                });
              },
              child: Container(
                  alignment: Alignment.center,
                  margin:
                  const EdgeInsets.only(top: 16, bottom: 10),
                  child: Text(
                    address.planned??'',
                    style: const TextStyle(
                        color: Color(0xFF333333), fontSize: 14),
                  )),
            );
          }),
    ));
  }

  Widget generateBottomBtn(){
    return SizedBox(
      height: 124,
      child: Column(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              if(currentTopIndex == 0 && topList.isNotEmpty){
                currentTopIndex = topList.length - 1;
                bottomList = findBottomList();
                setState(() {});
                return;
              }
              String address = "";
              for (var element in topList) {
                if(element == topList.last){
                  address += element;
                }else {
                  address += "$element|";
                }
              }
              widget.callBack(address);
              Get.back();
            },
            child: Container(
              margin: const EdgeInsets.only(top: 29, left: 20, right: 20),
              height: 47,
              width: double.infinity,
              alignment: Alignment.center,
              decoration: const BoxDecoration(
                color: Color(0xFF000000),
                borderRadius: BorderRadius.all(Radius.circular(8)),
                image: DecorationImage(
                  image: AssetImage('assets/address/ic_address_arrow.png'),
                ),
              ),
              child: Text(
                FMLanguageTool.getText('Confirm'),
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ),
          ),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              Get.back();
            },
            child: Container(
              margin: const EdgeInsets.only(top: 10),
              alignment: Alignment.center,
              child: Text(
                FMLanguageTool.getText('Cancel'),
                style: const TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 16,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  List<String> initTopList(List<FMAddressMySelfEntity> list,List<String> topList){
    if(list.isNotEmpty){
      topList.add(list.first.planned??"");
      List<FMAddressMySelfEntity> nextList = list.first.myself??[];
      return initTopList(nextList, topList);
    }
    return topList;
  }

  List<String> findTopList(List<FMAddressMySelfEntity> list,List<String> topList){
    for (var value in list) {
      if(value.planned == topList.last){
        List<FMAddressMySelfEntity> self = value.myself??[];
        if(self.isNotEmpty){
          topList.add(self.first.planned??'');
          findTopList(self, topList);
        }
      }
    }
    return topList;
  }

  List<FMAddressMySelfEntity> findBottomList(){
    if(currentTopIndex == 0){
      return allList;
    }else if(currentTopIndex == 1){
      for (var element in allList) {
        if(element.planned == topList[0]){
          return element.myself??[];
        }
      }
    }else if(currentTopIndex == 2){
      for (var element in allList) {
        if(element.planned == topList[0]){
          List<FMAddressMySelfEntity> self = element.myself??[];
          for (var item in self) {
            if(item.planned == topList[1]){
              return item.myself??[];
            }
          }
        }
      }
    }
    return [];
  }
}
